package com.share.order.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.domain.R;
import com.share.common.security.utils.SecurityUtils;
import com.share.order.domain.EndOrderVo;
import com.share.order.domain.OrderBill;
import com.share.order.domain.OrderInfo;
import com.share.order.domain.SubmitOrderVo;
import com.share.order.mapper.OrderBillMapper;
import com.share.order.mapper.OrderInfoMapper;
import com.share.order.service.IOrderInfoService;
import com.share.rule.api.RemoteFeeRuleService;
import com.share.rule.domain.FeeRule;
import com.share.rule.domain.FeeRuleRequestForm;
import com.share.rule.domain.FeeRuleResponseVo;
import com.share.user.api.RemoteUserService;
import com.share.user.domain.UserInfo;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-02-22
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RemoteFeeRuleService remoteFeeRuleService;

    @Autowired
    private RemoteUserService remoteUserInfoService;

    @Autowired
    private OrderBillMapper orderBillMapper;

    //获取未完成订单
    @Override
    public OrderInfo getNoFinishOrder(Long userId) {
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(OrderInfo::getUserId, userId);
        wrapper.eq(OrderInfo::getStatus, Arrays.asList("0", "1"));
        wrapper.orderByDesc(OrderInfo::getId);
        wrapper.last("limit 1");
        //调用
        OrderInfo orderInfo = baseMapper.selectOne(wrapper);
        return orderInfo;

    }

    //生成订单
    @Override
    public Long saveOrder(SubmitOrderVo submitOrderVo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(submitOrderVo.getUserId());
        orderInfo.setOrderNo(RandomUtil.randomString(8));
        orderInfo.setPowerBankNo(submitOrderVo.getPowerBankNo());
        orderInfo.setStartTime(new Date());
        orderInfo.setStartStationId(submitOrderVo.getStartStationId());
        orderInfo.setStartStationName(submitOrderVo.getStartStationName());
        orderInfo.setStartCabinetNo(submitOrderVo.getStartCabinetNo());
        // 费用规则
        FeeRule feeRule = remoteFeeRuleService.getFeeRule(submitOrderVo.getFeeRuleId()).getData();
        orderInfo.setFeeRuleId(submitOrderVo.getFeeRuleId());
        orderInfo.setFeeRule(feeRule.getDescription());
        orderInfo.setStatus("0");
        orderInfo.setCreateTime(new Date());
        orderInfo.setCreateBy(SecurityUtils.getUsername());
        //用户昵称
        UserInfo userInfo = remoteUserInfoService.getInfo(orderInfo.getUserId()).getData();
        orderInfo.setNickName(userInfo.getNickname());

        baseMapper.insert(orderInfo);
        return orderInfo.getId();
    }

    //结束订单
    @Override
    public void endOrder(EndOrderVo endOrderVo) {
        //1 根据充电宝的编号 + 订单状态 （充电中） 查询是否存在，如果不存在没有订单，直接返回
        // 如果存在正在充电的订单，把订单结束
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getPowerBankNo, endOrderVo.getPowerBankNo());
        wrapper.eq(OrderInfo::getStatus, "0");
        OrderInfo orderInfo = baseMapper.selectOne(wrapper);
        //判断
        if (orderInfo == null) { //如果不存在没有订单，直接返回
            return;
        }

        //2 设置订单的相关的数据进行更新
        orderInfo.setEndTime(endOrderVo.getEndTime());
        orderInfo.setEndStationId(endOrderVo.getEndStationId());
        orderInfo.setEndStationName(endOrderVo.getEndStationName());
        orderInfo.setEndCabinetNo(endOrderVo.getEndCabinetNo());
        // 包含充电的时长 以分钟为单位
        Date startTime = orderInfo.getStartTime();
        Date endTime = orderInfo.getEndTime();
        int duration = Minutes.minutesBetween(new DateTime(startTime), new DateTime(endTime)).getMinutes();
        orderInfo.setDuration(duration);

        //远程调用  规则引擎进行费用计算
        FeeRuleRequestForm feeRuleRequestForm = new FeeRuleRequestForm();
        feeRuleRequestForm.setDuration(duration);
        feeRuleRequestForm.setFeeRuleId(orderInfo.getFeeRuleId());

        //远程调用
        R<FeeRuleResponseVo> feeRuleResponseVoR = remoteFeeRuleService.calculateOrderFee(feeRuleRequestForm);
        FeeRuleResponseVo feeRuleResponseVo = feeRuleResponseVoR.getData();

        //设置费用
        orderInfo.setTotalAmount(feeRuleResponseVo.getTotalAmount());
        orderInfo.setDeductAmount(new BigDecimal("0"));
        orderInfo.setRealAmount(feeRuleResponseVo.getTotalAmount());

        if (orderInfo.getRealAmount().subtract(new BigDecimal(0)).doubleValue() == 0) {
            orderInfo.setStatus("2");
        } else {
            orderInfo.setStatus("1");
        }
        baseMapper.updateById(orderInfo);

        //3 插入免费的账单数据
        OrderBill feeOrderBill = new OrderBill();
        feeOrderBill.setOrderId(orderInfo.getId());
        feeOrderBill.setBillItem(feeRuleResponseVo.getFreeDescription());
        feeOrderBill.setBillAmount(new BigDecimal(0));
        orderBillMapper.insert(feeOrderBill);

        //4 插入收费账单数据（超过免费时间账单数据）
        BigDecimal exceedPrice = feeRuleResponseVo.getExceedPrice();
        if (exceedPrice.doubleValue() > 0) {
            OrderBill exceedOrderBill = new OrderBill();
            feeOrderBill.setOrderId(orderInfo.getId());
            feeOrderBill.setBillItem(feeRuleResponseVo.getFreeDescription());
            feeOrderBill.setBillAmount(feeRuleResponseVo.getExceedPrice());
            orderBillMapper.insert(exceedOrderBill);
        }
    }
}
